/**
 * tabBar页面路径列表 (用于链接跳转时判断)
 * tabBarLinks为常量, 无需修改
 * this.$app.方法名
 */
import Store from "@/store"
import util from "@/common/js/util.js"
// #ifdef H5
import wxApi from "@/common/js/wxApi.js"
// import manifest from "@/manifest.json"
// #endif
import siteinfo from "@/siteinfo.js";
const tabBarLinks = [
	'pages/tabbar/info/index',
	'pages/tabbar/myCenter/index',
];
const Base64 = util.Base64;

// 工具类

let App = {
	/**
	 * 全局变量
	 */
	globalData: {
		user_id: null,
	},
	// api地址
	api_root: '',
	scanCode: false,
	aid: '',
	// 图片地址
	img_root: '',
	imgfix: '',
	siteInfo: {},
	postData: {},
	loginstate: false,
	base: null,
	routers: null,
	/**
	 * LRC
	 * 初始化，获取地址和个人信息
	 */
	getInt() {
		let APP = this,
			user_token = uni.getStorageSync('user_token');
		// console.log("getInt", user_token);
		// if (!user_token) {
		// 	//进行自动登录
		// 	APP.doLogin(function(data) {
		// 		//登录成功，更新用户信息
		// 		APP.getUserInfo(data);
		// 	});
		// } else {
		// 	//刷新用户信息
		// 	APP.getUserInfo(user_token);
		// }
		//每次进系统都进行自动登录
		APP.doLogin(function(data) {
			//登录成功，更新用户信息
			APP.getUserInfo(data);
		});
	},
	/**
	 * LRC 根据openid刷新用户信息
	 * @param {Object} data
	 */
	getUserInfo(data) {
		let APP = this,
			openid = data.openid;
		APP._get("user.info", {
			openid: openid
		}, function(res) {
			//缓存
			uni.setStorageSync('user_token', res);
			uni.setStorageSync('openid', openid)
		})
	},

	/**
	 * 初始化用户的建档信息，将其存在本地存储中
	 */
	initCard(data) {
		console.log('initCard:' + JSON.stringify(data))
		let APP = this,
			openid = data.openid;
		uni.setStorageSync('user_cardlist', data.card_list)
		let user_cardlist = uni.getStorageSync('user_cardlist')
		
		if (user_cardlist && user_cardlist.length > 0) {
			uni.setStorageSync('current_user_card', data.card_list[0])
		}else {
			uni.setStorageSync('current_user_card', {names: ''})
		}
		
		// if (!uni.getStorageSync('current_user_card')) {
		// 	uni.setStorageSync('current_user_card', data.card_list[0])
		// }

		/* APP._get('entry/wxapp/apipatient.cardlist', {openid: openid}, (res)=>{
			console.log('卡列表')
			console.log(res)
			if (res.status == 1) {
				let cards = res.data
				uni.setStorageSync('user_cardinfo', {
					cardid: cards[0].cardid,
					cardName: cards[0].name
				})
			}
			
		}) */

	},

	/**
	 * LRC
	 * @param {Object} url 请求地址转换
	 */
	transformUrl(url) {
		//处理url
		let p = url.split("/");
		if (p.length >= 3) {
			url = "&c=" + p[0] + "&from=" + p[1] + "&act=" + p[2];
		} else if (p.length == 1) {
			url = "&c=entry&from=wxapp&act=" + p[0];
		}
		url += '&do=copysite&m=' + this.siteInfo.name + '&a=' + this.siteInfo.channel
		return this.api_root + url;
	},

	/**
	 * LRC
	 * get请求 
	 */
	_get(url, data, success, fail, complete) {
		this.weRequest("GET", url, data, success, fail, complete)
	},

	/**
	 * LRC
	 * post提交
	 */
	_post_form(url, data, success, fail, complete) {
		this.weRequest("POST", url, data, success, fail, complete)
		// this.inspectOpenId().then(() => {
		// 	this.weRequest("POST", url, data, success, fail, complete)
		// })
	},

	_post_form2(url, data, success, fail, complete) {
		this.weRequest2("POST", url, data, success, fail, complete)
		// this.inspectOpenId().then(() => {
		// 	this.weRequest2("POST", url, data, success, fail, complete)
		// })
	},

	/**
	 * 检查本地缓存是否存在openid，不存在的话重新授权
	 */
	inspectOpenId() {
		return new Promise((resolve) => {
			// 这里放置需要同步执行的逻辑
			console.log('检查本地缓存是否存在openid')
			let openid = uni.getStorageSync('openid')
			if (!openid) {
				console.log('本地openid为空，重新授权')
				// uni.showToast({
				// 	icon: 'none',
				// 	title: '检测到您尚未授权微信登录，请点击右上角图标然后选择重新加载小程序'
				// })
				// this.getInt()
				let APP = this
				APP.doLogin(function(data) {
					APP._get("user.info", {
						openid: data.openid
					}, function(res) {
						//缓存
						uni.setStorageSync('user_token', res);
						uni.setStorageSync('openid', res.openid)
					})
				});
			}

			resolve(); // 当所有操作完成后调用 resolve() 表示已经同步执行完成
		})
	},

	/**
	 * LRC
	 * @param {Object} method
	 * @param {Object} url
	 * @param {Object} data
	 * @param {Object} success
	 * @param {Object} fail
	 * @param {Object} complete
	 */
	weRequest(method, url, data, success, fail, complete) {
		let App = this,
			// uniacid = App.getUniacid(),
			requestUrl = App.transformUrl(url),
			pages = getCurrentPages(),
			currentRegion = uni.getStorageSync('currentRegion'),
			agencyData = uni.getStorageSync('agencyData'),
			token = uni.getStorageSync('user_token'),
			source = App.getClientType(), //1公众号 2H5	3微信小程序
			loginTimer = null;
		// console.log(url.indexOf('&p=dating') == -1?requestUrl:requestUrl + '&dating_head_id=' + uni.getStorageSync('dating_head_id'),'当前请求');
		// 构造请求参数
		data = data || {};
		data.do = data.do || 'copysite';
		data.m = this.siteInfo.name;
		data.v = this.siteInfo.weliamv;
		data.a = this.siteInfo.channel;
		data.hid = this.siteInfo.hid;
		console.log(requestUrl);
		// data.wxapp_id = App.siteInfo.uniacid;
		// data.aid = this.aid || agencyData.aid || "";
		// data.token = uni.getStorageSync('user_token');
		// data.source = source;

		// //#ifdef APP-PLUS
		// data.source = "3";
		// //#endif
		// //#ifdef H5
		// data.source = "4";
		// //#endif
		uni.showLoading({
			title: '加载中',
			mask: true
		});
		uni.request({
			url: requestUrl,
			header: {
				'content-type': method === "POST" ? 'application/x-www-form-urlencoded' :
					"application/json",
			},
			method: method,
			data: data,
			success(res) {
				//#ifdef H5
				let post = requestUrl.split('&do=')[1];
				let local;
				let onoption;

				//#endif

				success && success(res.data);
				uni.hideLoading()
			},
			fail(res) {
				uni.hideLoading()
			},
			complete(res) {
				complete && complete(res);
				uni.hideLoading()
			}
		});
	},
	weRequest2(method, url, data, success, fail, complete) {
		let App = this,
			// uniacid = App.getUniacid(),
			requestUrl = App.transformUrl(url),
			pages = getCurrentPages(),
			currentRegion = uni.getStorageSync('currentRegion'),
			agencyData = uni.getStorageSync('agencyData'),
			token = uni.getStorageSync('user_token'),
			source = App.getClientType(), //1公众号 2H5	3微信小程序
			loginTimer = null;
		// console.log(url.indexOf('&p=dating') == -1?requestUrl:requestUrl + '&dating_head_id=' + uni.getStorageSync('dating_head_id'),'当前请求');
		// 构造请求参数
		data = data || {};
		data.do = data.do || 'copysite';
		data.m = this.siteInfo.name;
		data.v = this.siteInfo.weliamv;
		data.a = this.siteInfo.channel;
		data.hid = this.siteInfo.hid;
		console.log(requestUrl);
		// data.wxapp_id = App.siteInfo.uniacid;
		// data.aid = this.aid || agencyData.aid || "";
		// data.token = uni.getStorageSync('user_token');
		// data.source = source;

		// //#ifdef APP-PLUS
		// data.source = "3";
		// //#endif
		// //#ifdef H5
		// data.source = "4";
		// //#endif
		uni.showLoading({
			title: '加载中',
			mask: true
		});
		uni.request({
			url: requestUrl,
			header: {
				'content-type': method === "POST" ? 'application/x-www-data-urlencoded' :
					"application/json",
			},
			method: method,
			data: data,
			success(res) {
				//#ifdef H5
				let post = requestUrl.split('&do=')[1];
				let local;
				let onoption;

				//#endif

				success && success(res.data);
				uni.hideLoading()
			},
			fail(res) {
				uni.hideLoading()
			},
			complete(res) {
				complete && complete(res);
				uni.hideLoading()
			}
		});
	},
	/**
	 * LRC
	 * 执行用户登录
	 */
	doLogin(func) {
		// 保存当前页面
		let APP = this,
			clientType = APP.getClientType();
		console.log("doLogin", clientType);
		if (clientType == 3) {
			//小程序登录
			uni.login({
				"provider": "weixin",
				"onlyAuthorize": true, // 微信登录仅请求授权认证
				success: function(event) {
					const {
						code
					} = event
					console.log('登录授权：', event);
					// 获取用户信息
					APP._get("authorize.getuid", {
						code: code
					}, function(res) {
						console.log('微信自动')
						console.log(res);
						let openid = res.openid;
						let data = {
							openid: openid,
							u_name: '游客',
							u_thumb: APP.siteInfo.siteroot +
								'/attachment/avatar.png',
						}
						// 保存用户session_key
						uni.setStorageSync('session_key', res.userinfo.session_key)
						//进行用户注册
						APP._get("authorize.tymember", data, function(res) {
							if (func) {
								func({
									...data,
									...res
								});
							}
						});

						APP.initCard(res)
					}, function(res) {
						console.log(res);
					});
				},
				fail: function(err) {
					// 登录授权失败  
					// err.code是错误码
				}
			})
		}
	},
	/**
	 * LRC
	 * 设置项目基础信息
	 */
	setSiteInfo() {
		// uni.setStorageSync('head_id', '24')
		console.log(siteinfo);
		this.base = siteinfo.base;
		this.routers = siteinfo.routers;
		// #ifdef H5
		let url = location.href,
			uniacid;

		if (location.href.indexOf("/h5/?#/pages/") === -1) {
			let reg = new RegExp("\/h5/.*?\#/");
			url = url.replace(reg, "/h5/#/");
		}
		//获取当前请求域名
		console.log(url);
		uniacid = util.getParams("i", url.split("#")[1], true);
		if (uniacid == 'undefined') {
			uniacid = siteinfo.uniacid;
		}
		let siteroot = location.protocol + "//" + location.hostname,
			sitetoken = App.getClientType(),
			token = (sitetoken == 1) ? App.getCookie("user_token") : uni.getStorageSync('user_token'),
			head_id = (location.href.indexOf("&token") === -1 ? location.href.split("head_id=")[1] :
				location.href
				.split("&")[
					1].split("head_id=")[1]) || "";
		let head_ids = head_id.split("&")[0];
		if (head_id && !!head_id) {
			// debugger
			uni.setStorageSync('head_id', head_ids);
			uni.setStorageSync('dating_head_id', head_ids);
		};

		this.siteInfo = {
			...siteinfo,
			...{
				siteroot: "/app",
				name: siteinfo.name,
				uniacid,
				weliamv: siteinfo.weliamv,
				token
			}
		}
		url = url.split("&token=")[0];
		history.replaceState(null, null, `${this.base}#` + url.split("#")[1]);
		if (url.indexOf('pages/mainPages/postDetails/postDetails') != -1) {
			// 
			let urls = url.split('/#/')[1];
			urls = urls.replace('mainPages', "subPages");
			this.navigationTo({
				url: urls
			});
			return
		}
		// #endif
		// #ifndef H5
		this.siteInfo = siteinfo;
		// #endif
		this.imgfix = uni.getStorageSync('imgPrefix');
	},




	/**
	 * 设置api地址
	 */
	setAppRoot(aids) {
		this.aid = aids + ',';
		let App = this,
			siteroot = null,
			postData = {
				source: "1",
				mode: "2",
			},
			user_token = this.getCookie("user_token");
		siteroot = this.siteInfo.siteroot + `${this.routers}`;
		this.aid = this.aid.replace(/,/g, '');
		this.api_root = siteroot + 'index.php?i=' + this.siteInfo.uniacid + (!!this.siteInfo.token ?
			'&token=' +
			this.siteInfo.token : '');
		if (this.api_root.indexOf('aid') === -1) {
			this.api_root + '&aid=' + this.aid;
		}
		this.img_root = this.siteInfo.siteroot + `${this.base}/resource/image/`;
		let apiObj = this.urlToObj(this.api_root);
		if (!!apiObj.token && apiObj.token !== "undefined") {
			uni.setStorageSync('user_token', apiObj.token)
		} else {
			// this._post_form('&p=member&do=login&source=1&mode=2', {}, (res) => {
			// 	console.log(res);
			// });
		}
		console.log(this.api_root);
	},
	/**
	 * 小程序启动场景
	 */
	onStartupScene(query) {
		if (query && !!query.head_id) {
			// debugger
			uni.setStorageSync('head_id', query.head_id);
			uni.setStorageSync('dating_head_id', query.head_id);
		}
	},
	/**
	 * 获取小程序信息
	 */
	updateAppInfo() {
		let App = this;
		App._post_form('&do=GetPlatformInfor', {}, function(result) {
			Store.commit("APPINFO", result.data);
			uni.setStorage({
				key: 'phone',
				data: result.data.phone,
				success: function() {}
			});
			uni.removeStorageSync('platformInfor');
			uni.setStorage({
				key: 'platformInfor',
				data: result.data,
				success: function() {}
			});
		});
	},

	//更新提示
	up() {
		const updateManager = uni.getUpdateManager();

		updateManager.onCheckForUpdate(function(res) {
			// 请求完新版本信息的回调
			console.log(res.hasUpdate);
		});

		updateManager.onUpdateReady(function(res) {
			uni.showModal({
				title: '更新提示',
				content: '新版本已经准备好，是否重启应用？',
				success(res) {
					if (res.confirm) {
						// 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
						updateManager.applyUpdate();
					}
				}
			});

		});

		updateManager.onUpdateFailed(function(res) {
			// 新的版本下载失败;
			uni.showModal({
				title: '升级失败',
				content: '新版本下载失败，请检查网络！',
				showCancel: false
			});
		});

	},

	//获取用户设置
	userSettings() {
		let App = this;
		App._post_form('&do=CustomerService', {}, function(result) {
			uni.removeStorageSync('CustomerService');
			uni.removeStorageSync('btnleftAndbottom');
			let ratio;
			uni.getSystemInfo({
				success: function(wh) {
					ratio = wh.windowWidth / result.data.imgstyle.width;
				}
			});
			let imgstyle = {
				width: ratio * result.data.imgstyle.width,
				height: ratio * result.data.imgstyle.height
			};
			uni.setStorageSync('imgstyle', imgstyle);


			let ratios;
			uni.getSystemInfo({
				success: function(wh) {
					ratios = wh.windowWidth / result.data.listimgstyle.width;
				}
			});
			let listimgstyle = {
				width: ratios * result.data.listimgstyle.width,
				height: ratios * result.data.listimgstyle.height
			};
			uni.setStorageSync('listimgstyle', listimgstyle);
			uni.setStorageSync('CustomerService', result.data);
		});
	},
	//SDK经纬度获取
	wxApiCallback(path) {
		let _this = this;
		uni.removeStorageSync('memberCityAreaid');
		// #ifdef H5
		wxApi.wxRegister(() => {
			jWeixin.getLocation({
				type: 'gcj02',
				success: function(res) {
					uni.setStorageSync('curLoction', res);
					let data = {
						aid: this.aid,
						lat: res.latitude,
						lng: res.longitude
					}
					let curtimestamp = new Date()
						.getTime(); //当前时间					let lastredpackeTime = uni.getStorageSync('locationGetTime'); // 最后次红包窗口关闭时间;					let now_packetTime = !!lastredpackeTime ? ((curtimestamp - lastredpackeTime) / 1000 / 60 % 60) : "";
					if (!!now_packetTime && now_packetTime < 2) return
					if (path == 'pages/mainPages/index/index') {
						_this._post_form('&do=Aidtip', data, (reource) => {
							if (reource.data.status == 1) {
								_this.showError(
									`定位到您在${reource.data.memberCityName},是否切换到该地区?`,
									data => {
										if (data.confirm) {
											uni.setStorageSync(
												'memberCityAreaid',
												reource.data
												.memberCityAreaid);
											_this.setAppRoot(reource
												.data
												.memberCityAid);
											App.navigationToH5(false,
												`${this.base}#/?i=${_this.siteInfo.uniacid}&aid=${reource.data.memberCityAid}`
											);
											window.location.reload();
										} else {
											let timestamp = (new Date())
												.getTime();
											uni.setStorageSync(
												'locationGetTime',
												timestamp)
										}
									},
									true
								);
							}
							return
						})
					}
				}
			});
		})
		// #endif
		// #ifndef H5
		// App.getLocation().then(res => {
		// 	let data = {
		// 		aid: this.aid,
		// 		lat: res.latitude,
		// 		lng: res.longitude
		// 	}
		// 	let curtimestamp = new Date().getTime(); //当前时间
		// 	let lastredpackeTime = uni.getStorageSync('locationGetTime'); // 最后次红包窗口关闭时间;
		// 	let now_packetTime = !!lastredpackeTime ? ((curtimestamp - lastredpackeTime) / 1000 / 60 % 60) : "";
		// 	if(!!now_packetTime && now_packetTime < 2) return
		// 	if(path == 'pages/mainPages/index/index'){
		// 		_this._post_form('&do=Aidtip', data, (reource) => {
		// 			uni.setStorageSync('curLoction', res);
		// 			if(reource.data.status == 1){
		// 				_this.showError(
		// 					`定位到您在${reource.data.memberCityName},是否切换到该地区?`,
		// 					data => {
		// 						if (data.confirm) {
		// 							uni.setStorageSync('memberCityAreaid',reource.data.memberCityAreaid);
		// 							_this.setAppRoot(reource.data.memberCityAid);
		// 							App.navigationTo({
		// 								url: 'pages/mainPages/index/index'
		// 							});
		// 						}else{
		// 									let timestamp = (new Date()).getTime();											uni.setStorageSync('locationGetTime', timestamp)
		// 								}
		// 					},
		// 					true
		// 				);
		// 			}

		// 		})
		// 	}
		// })
		// #endif
	},

	/**
	 * 跳转链接转换
	 */
	navgatetoLink() {
		let App = this;
		App._post_form('&do=TransformationLink', {}, (res) => {
			uni.setStorageSync('pagelinkList', res.data);
		})
	},
	getCookie(cookieName) {
		// #ifdef H5
		let cookies = document.cookie,
			cookiesArr = cookies.split(";");
		for (let i = 0; i < cookiesArr.length; i++) {
			let arr = cookiesArr[i].split("=");
			arr[0] = arr[0].replace(/ /g, '')
			if (arr[0] === cookieName) {
				return arr[1];
			}
		}
		return "";
		// #endif
		return "";
	},
	getuserToken() {
		return uni.getStorageSync('user_token')
	},
	/**
	 * 获取tabBar页面路径列表
	 */
	getTabBarLinks() {
		return tabBarLinks;
	},
	/**
	 * 微信公众号登陆
	 */
	openWxLogin(Navurl) {
		let App = this;
		// #ifdef H5
		location.href = Navurl;
		// #endif
	},
	/**
	 * 判断当前客户端类型
	 */
	getClientType() {
		// 1 公众号 2h5 3微信
		// #ifdef MP-WEIXIN
		return "3";
		// #endif

		// #ifdef H5
		let ua = navigator.userAgent.toLowerCase(); //获取判断用的对象
		if (ua.match(/MicroMessenger/i) == "micromessenger") {
			return "1";
		}
		return "2";
		// #endif

		//#ifdef APP-PLUS
		return "3";
		//#endif
	},

	// 获取浏览器内核版本号

	getBrowser(n) {
		// #ifdef H5
		let ua = navigator.userAgent.toLowerCase(),
			s,
			name = '',
			ver = 0;
		//探测浏览器
		(s = ua.match(/msie ([\d.]+)/)) ? _set("ie", _toFixedVersion(s[1])):
			(s = ua.match(/firefox\/([\d.]+)/)) ? _set("firefox", _toFixedVersion(s[1])) :
			(s = ua.match(/chrome\/([\d.]+)/)) ? _set("chrome", _toFixedVersion(s[1])) :
			(s = ua.match(/opera.([\d.]+)/)) ? _set("opera", _toFixedVersion(s[1])) :
			(s = ua.match(/version\/([\d.]+).*safari/)) ? _set("safari", _toFixedVersion(s[1])) : 0;

		function _toFixedVersion(ver, floatLength) {
			ver = ('' + ver).replace(/_/g, '.');
			floatLength = floatLength || 1;
			ver = String(ver).split('.');
			ver = ver[0] + '.' + (ver[1] || '0');
			ver = Number(ver).toFixed(floatLength);
			return ver;
		}

		function _set(bname, bver) {
			name = bname;
			ver = bver;
		}
		return (n == 'n' ? name : (n == 'v' ? ver : name + ver));
		//getBrowser("n"); // 所获得的就是浏览器所用内核。
		//getBrowser("v");// 所获得的就是浏览器的版本号。
		//getBrowser();// 所获得的就是浏览器内核加版本号。
		// #endif
	},

	/**
	 * 验证是否存在user_info
	 */
	validateUserInfo() {
		let user_info = uni.getStorageSync('userInfo');
		return !!uni.getStorageSync('userInfo');
	},

	/**
	 * 显示成功提示框
	 */
	showSuccess(msg, callback) {
		uni.showToast({
			title: msg,
			icon: 'success',
			mask: true,
			duration: 1500,
			success() {
				callback && (setTimeout(function() {
					callback();
				}, 1500));
			}
		});
	},

	/**
	 * 显示失败提示框
	 */
	showError(msg, callback, showCancel = false) {
		uni.showModal({
			title: '友情提示',
			content: msg,
			showCancel: showCancel,
			success(res) {
				callback && callback(res);
			}
		});
	},

	// 推荐人id 
	saveRefereeId() {
		if (!!Store.state.recomid) {
			return Store.state.recomid
		}
	},
	getImgUrl() {
		let App = this;
		let a = this.siteInfo.uniacid;
		App._post_form('&do=GetimgPrefix', {}, res => {
			App.imgfix = res.data.imgPrefix;
			uni.setStorageSync('imgPrefix', res.data.imgPrefix);
			return App.imgfix
		});

	},
	clipboard(data) {
		const textarea = document.createElement('textarea');
		textarea.value = data;
		textarea.readOnly = 'readOnly';
		document.body.appendChild(textarea);
		textarea.select();
		textarea.setSelectionRange(0, data.length);
		document.execCommand('copy');
		textarea.remove();
		textarea.style.display = "none";
		uni.showToast({
			icon: 'none',
			title: '复制成功'
		})
	},
	getSetInfo() {
		let data = {
			type: 0
		}
		uni.setStorageSync('getSetInfo', data);
		let App = this;
		App._post_form('&p=Im&do=getSetInfo', {}, res => {
			console.log(res)
			uni.setStorageSync('getSetInfo', res.data);
		});

	},
	getAreaId(location = "", cityname = "", areaid = "", callback, isSwitchCity = false) {
		let memberCityAreaid = uni.getStorageSync('memberCityAreaid');
		let App = this,
			pages = getCurrentPages(),
			navType = pages.length > 1 ? 'reLaunch' : 'navigate',

			// requestData = {
			// 	lat: !!location.lat ? (location.lat || location.latitude) : "",
			// 	lng: !!location.lng ? (location.lng || location.longitude) : "",
			// 	cityname,
			// 	areaid,
			// };

			requestData = {
				lat: location.lat || location.latitude || "",
				lng: location.lng || location.longitude || "",
				cityname,
				areaid: areaid || memberCityAreaid
			};
		App._post_form('&do=GetAid', requestData, res => {
			this.aid = res.data.aid;
			if (res.data.status === 1 || res.data.status === 2) {
				let agencyData = {
					areaname: res.data.areaname,
					aid: "",
					lat: res.data.lat,
					lng: res.data.lng
				};
				if (location) {
					uni.setStorageSync('agencyData', res.data);
				} else {
					uni.setStorageSync('agencyData', agencyData);
				}

				App.setAppRoot(agencyData.aid);
				App.getImgUrl()
				App.navigationTo({
					url: `pages/mainPages/notOpen/notOpen?city_agent_status=${res.data.status}&city_agent_name=${res.data.name}&joinPhone=${res.data.phone}`,
					navType
				})
				return false;
			} else if (res.data.status === 3) {
				App.navigationTo({
					url: `pages/mainPages/city/city`,
					navType
				})
			} else {
				if (!isSwitchCity) {
					uni.setStorageSync('agencyData', res.data);
					App.setAppRoot(res.data.aid);
				}
				callback && callback(res)
			}
		})
	},
	wxShareInfo() {
		let App = this;
		App._post_form('&do=Shareinfo', {}, res => {
			Store.commit('MPSHAREINFO', res.data)
		})
	},
	dealershareInfo(callback, type = "11") {
		let App = this;
		App._post_form('&do=Shareinfo', {
			type
		}, res => {
			callback && callback(res)
		})
	},
	/**
	 * 清除登录缓存
	 */
	removeCurrentPage() {
		uni.removeStorageSync("currentPage");
	},
	/**
	 * 对象转URL
	 */
	urlEncode(data) {
		var _result = [];
		for (var key in data) {
			var value = data[key];
			if (value.constructor == Array) {
				value.forEach(function(_value) {
					_result.push(key + "=" + _value);
				});
			} else {
				_result.push(key + '=' + value);
			}
		}
		return _result.join('&');
	},
	/**
	 * url转对象
	 */
	urlToObj(str) {
		var obj = {};
		var arr1 = str.split("?");
		var arr2 = arr1[1].split("&");
		for (var i = 0; i < arr2.length; i++) {
			var res = arr2[i].split("=");
			obj[res[0]] = res[1];
		}
		return obj;
	},

	/**
	 * 获取url参数
	 */
	getQueryString(name, url) {
		let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
		let r = url.substr(1).match(reg);
		if (r != null) {
			return unescape(r[2]);
		}
		return null;
		8
	},
	/**
	 * 通用指定跳转链接方法
	 * url:跳转链接 navType:{navigate,rediRect,reLaunch,wxParse富文本}跳转方法, pageUrl 是否使用接口路径  success跳转成功回调
	 */
	navigationTo({
		url,
		navType = 'navigate',
		success
	}) {
		let App = this,
			tabBarLinks = App.getTabBarLinks(),
			isTabBar = tabBarLinks.includes(url),
			pageUrl = url.indexOf('http') !== -1 || url.indexOf('./index') !== -1,
			isprogram = url.indexOf('appid') !== -1 || url.indexOf('appurl') !== -1,
			istel = url.indexOf('tel') !== -1,
			indet = url.indexOf('indet') !== -1;

		// if(url.indexOf('aid') != -1){
		// 	this.aid = this.getQueryString('aid',url.split('?')[1]);
		// 	this.setAppRoot(this.aid);
		// }
		// // debugger
		// if(indet){

		// 	App.navigationToH5(false, url);
		// 	return
		// }
		// #ifndef H5
		if (isprogram) {
			let parmsArr = url.split(','),
				appId = parmsArr[0].split('appid:')[1],
				path = parmsArr[1].split('appurl:')[1];
			if (!!appId && !!path) {
				uni.navigateToMiniProgram({
					appId,
					path,
					success(res) {
						console.log('success', res)
						// 打开成功
					},
					fail(err) {
						console.log('err', err)
					}
				})
			}
		};
		// #endif
		if (istel) {
			let tel = url.split("tel:")[1];
			uni.makePhoneCall({
				phoneNumber: tel
			})
		};
		if (navType === 'wxParse') {
			location.href = url
		};
		if (pageUrl) {
			// #ifndef H5
			url = encodeURIComponent(url)
			uni.redirectTo({
				url: `/pages/subPages/webview/webview?urlsrc=${url}`
			});
			// #endif
			// #ifdef H5
			let pagelink_list = uni.getStorageSync('pagelinkList'),
				isPageIndex = url.indexOf('./index') !== -1,
				isParms = url.indexOf('?') !== -1;

			if (isParms) {
				let params = App.urlToObj(url),
					pageLine_name = `${params.p}/${params.ac}/${params.do}`;
				if (!!params['p'] && !!params['ac'] && !!params['do']) {
					for (let key in pagelink_list) {
						let isPage_link = pageLine_name.indexOf(key) !== -1;
						if (isPage_link) {
							let navUrl = pagelink_list[pageLine_name],
								newParams = params;
							delete newParams['p'];
							delete newParams['ac'];
							delete newParams['do'];
							delete newParams['c'];
							delete newParams['m'];
							navUrl += (navUrl.indexOf("?") !== -1 ? "&" : "?") + App.urlEncode(
								newParams);
							// tabBar页面

							if (isTabBar) {

								uni.redirectTo({
									url: '/' + navUrl
								})
							} else {
								// 普通页面
								uni.navigateTo({
									url: '/' + navUrl
								});
							}
						}
					}
				} else {
					location.href = url
				}
			} else {
				App.navigationToH5(isPageIndex, url)
			}
			// #endif
		} else {
			// #ifdef H5
			if (url.indexOf("i=") === -1) {
				url += (url.indexOf("?") !== -1 ? "&i=" : "?i=") + App.siteInfo.uniacid;
			}
			// #endif
			if (navType === 'navigate') {
				if (isTabBar) {
					uni.redirectTo({
						url: '/' + url
					})
				} else {
					// 普通页面
					uni.navigateTo({
						url: '/' + url
					});
				}
			} else if (navType === 'rediRect') {
				uni.redirectTo({
					url: '/' + url,
					success
				})
			} else if (navType === 'reLaunch') {
				uni.reLaunch({
					url: '/' + url,
					success
				})
			}
		}
	},
	// h5跳转
	navigationToH5(isPageIndex, url) {
		let App = this;
		// debugger
		if (isPageIndex) {
			// #ifdef H5
			let pageIndexUrl = `${App.api_root}${url.split("./")[1]}`;
			location.href = pageIndexUrl
			// #endif
		} else {
			// #ifdef H5
			location.href = url
			// #endif
		}
	},
	/**
	 * 记录formId
	 */
	saveFormId(temp_type) {
		let App = this;
		App._post_form('&do=TempId', {
			temp_type
		}, res => {
			let formList = res.data,
				idsArray = [];
			if (formList.length > 0) {
				formList.map((val => {
					idsArray.push(val.temp_id)
				}))
				let encodeFormList = JSON.stringify(formList),
					base = new Base64,
					encodeStr = base.encode(encodeFormList);
				uni.requestSubscribeMessage({
					tmplIds: idsArray,
					success(idsres) {
						let tmpIdsArray = [];
						for (let [key, val] of Object.entries(idsres)) {
							if (val === 'accept') {
								tmpIdsArray.push(key)
							}
						}
						App._post_form('&do=SetFromId', {
							form_id: tmpIdsArray,
							info: encodeStr
						}, res => {
							console.log(res)
						});
					},
					fail(err) {
						console.log(err)
					}
				})
			}
		})
	},
	//上传图片
	_upLoad(url) {
		let App = this;
		return new Promise((resolve, reject) => {
			uni.uploadFile({
				url: App.api_root + '&do=uploadFiles',
				filePath: url,
				fileType: "image",
				name: 'file',
				success(res) {
					if (res.statusCode !== 200 || typeof res.data !== 'string') {
						App.showError('网络请求出错');
						return false;
					} else {
						if (res.code === 0) {
							App.showError(res.data.msg);
							return false;
						} else {
							resolve(JSON.parse(res.data));
						}
					}
				},
				fail(res) {
					uni.hideLoading();
					uni.showModal({
						title: "上传失败",
						content: JSON.stringify(res),
						showCancel: false
					});
					reject();
				},
				complete() {
					uni.hideToast(); //隐藏Toast
				}
			})
		});
	},
	/**
	 * 获取当前页面栈
	 */
	getCurrentPage() {
		//1-导入 2-微信小程序 3-H5 4-公众号 5-安卓 6-苹果 7-渠道1小程序 8-百度小程序 9-头条小程序
		let App = this,
			pages = getCurrentPages(),
			clientType = App.getClientType(),
			currentPage = pages[pages.length - 1],
			pageInstance = null;
		if (clientType === "2" || clientType === "7" || clientType === "9") {
			pageInstance = currentPage.$vm;
		} else if (clientType === "3" || clientType === "4") {
			pageInstance = currentPage;
		} else {
			pageInstance = currentPage.rootVM;
		}
		return pageInstance;
	},

	/**
	 * 全屏加载
	 */
	// showLoading() {
	// 	let App = this,
	// 		page = App.getCurrentPage();
	// 	!!page.$refs.loading && page.$refs.loading.showLoading();
	// },
	// hideLoading(time = 500) {
	// 	let App = this,
	// 		page = App.getCurrentPage();
	// 	setTimeout(() => {
	// 		!!page.$refs.loading && page.$refs.loading.hideLoading();
	// 	}, time);
	// },

	/**
	 * 获取当前经纬度
	 */
	getLocation() {
		let App = this,
			clientType = App.getClientType();
		return new Promise((resolve, reject) => {
			let LocationType = clientType === "3" ? uni : wxApi;
			LocationType.getLocation({
				type: "gcj02", // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
				success(res) {
					resolve(res);
				},
				fail(res) {
					resolve({
						latitude: "",
						longitude: ""
					});
				},
				complete(res) {
					console.log(res);
				}
			});
		})
	},
	/**
	 * 查看位置
	 */
	openLocation(options) {
		let App = this;
		if (!!options.location) {
			// let gps = util.baidu_To_qq(options.latitude, options.longitude);
			uni.openLocation({
				name: options.storename,
				address: options.address,
				latitude: Number(options.location.lat),
				longitude: Number(options.location.lng),
				success() {
					options.success && options.success();
				}
			});
		} else {
			App.showError("经纬度信息不完整,请确认后重试");
		}
	},

	/**
	 * 商品富文本数据切割，避免一次性加载数据量超大
	 * @param {type}  
	 */
	// wxParseLazyLoad(padding = 0, content, dataKey) {
	// 	//商品富文本数据切割，避免一次性加载数据量超大
	// 	let sliceLen = 20, //懒加载数据切割长度
	// 		currentPage = this.getCurrentPage(),
	// 		transData = {}, //存放转化后的数据
	// 		bindData = {}, //存放当前绑定的数据
	// 		nodePage = 0,
	// 		nodesList = [],
	// 		imageProp = {
	// 			mode: 'aspectFit',
	// 			padding,
	// 			lazyLoad: false,
	// 			domain: '',
	// 		};
	// 	transData = HtmlToJson(content, {}, imageProp);
	// 	if (transData.nodes.length > sliceLen) {
	// 		let nodes = transData.nodes;
	// 		for (let i = 0, len = nodes.length; i < len; i += sliceLen) {
	// 			nodesList.push(nodes.slice(i, i + sliceLen));
	// 		}
	// 		bindData.imageUrls = transData.imageUrls;
	// 		bindData.nodes = nodesList[0];
	// 	} else {
	// 		bindData = transData;
	// 	}
	// 	currentPage[dataKey] = bindData;
	// 	if (nodesList.length > 0) {
	// 		for (let i = 1; i < nodesList.length; i++) {
	// 			setTimeout(() => {
	// 				currentPage[dataKey].nodes.push(...nodesList[i]);
	// 			}, 800);
	// 		}
	// 	}
	// },
}
export default {
	...App
}